// const host = process.env.NODE_ENV == 'development' ? 'http://192.168.1.133:10866' : 'http://119.23.49.169:10866'

import md5 from 'js-md5'
import store from '@/store/store.js'

let hostImg = '/uploads/images/' //图片域名
let shareImg = '/uploads/share/' //分享图片域名

const host = 'http://39.108.211.191:8080' //测试
// const host = 'http://192.168.2.174:8080' //正式
// const host = '/api' //跨域

let appUpdateAddr = ''

const http = (mode = 'GET', path, data) => {
	appUpdateAddr = path
	let token = uni.getStorageSync('userToken')
	let model = uni.getStorageSync('model')	//手机牌子、型号
	
	const header = {
		'Authorization': token ? `Bearer ${token}` : '',
		'equipment': `APP ${model}`//设备
	}
	
	// console.log(header,'header')
	
	return new Promise((resolve, reject) => {
		uni.request({
			header: header,
			method: mode,
			url: host + path,
			data,
			responseType: path == '/api/Contract/DownloadContract' ? 'arraybuffer' : '',
			complete: (res) => {
				// 判断状态码
				watchStatusCode(res, resolve, reject)
			}
		})
	})
}

// 文件上传(单个)
const upload = (url, data, file = 'img') => {
	uni.showLoading({
		title: '上传中...'
	})

	return new Promise((resolve, reject) => {
		let token = uni.getStorageSync('userToken')
		const host = uni.getStorageSync('url')
		uni.uploadFile({
			// header,
			url: host + url,
			filePath: data,
			name: file,
			success: res => {
				let datas = res.data
				uni.hideLoading()
				resolve(datas)
			},
			fail: err => {
				uni.hideLoading()
				uni.showToast({
					title: '图片上传失败，请压缩以后再上传',
					icon: 'none'
				})
				reject(err)
			}
		})
	})
}


// 判断状态码
const watchStatusCode = (res, resolve, reject) => {

	// console.log(JSON.stringify(res))

	switch (res.statusCode) {
		case 200: // 后端正常接收数据
			if (res.data.status == 200) { //为true提交的业务才算通过 
				resolve(res.data.data)
			} else if (res.data.status == 100500) {
				// uni.showToast({
				// 	icon: 'none',
				// 	title: '登录过期请重新登录'
				// })

				// setTimeout(() => {
					uni.setStorageSync('userToken', '');
					
					if(appUpdateAddr != '/user/appUpdateAddr.html'){
						store.dispatch('user/$LOGOUT')
					}
				// }, 2000)
			} else {
				if(appUpdateAddr == '/api/Contract/DownloadContract'){
					resolve(res.data)
				}else {
					reject(res)
				}
				if (res.data.message) {
					uni.showToast({
						icon: 'none',
						title: res.data.message,
						duration: 3000
					})
				}
			}
			break;
		default: // 其他错误
			reject(res.data)
			if (res.data.message) {
				uni.showToast({
					icon: 'none',
					title: res.data.message
				})
			}

			break;
	}
}


export default {
	http: {
		get: (url, data) => http('GET', url, data),
		post: (url, data) => http('POST', url, data),
		put: (url, data) => http('PUT', url, data),

		upload: (url, data) => upload(url, data)
	},
	hostImg,
	shareImg
}
